#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <unistd.h>
#include <pthread.h>

// 售票系统代码mutex

class ThreadData
{
public:
    ThreadData(const char *name, pthread_mutex_t &lock)
        : _name(name), _plock(&lock)
    {
    }
    ~ThreadData() {}

    const char *GetName()
    {
        return _name.c_str();
    }

    pthread_mutex_t *GetPlock()
    {
        return _plock;
    }

private:
    std::string _name;
    pthread_mutex_t *_plock;
};

int ticket = 100;
void *route(void *args)
{
    ThreadData *td = static_cast<ThreadData *>(args);
    while (1)
    {
        // 加锁：尽量我们加锁范围粒度要比较细，尽可能地不要包含太多非临界区的代码
        pthread_mutex_lock(td->GetPlock());
        if (ticket > 0)
        {
            usleep(1000);
            printf("%s sells ticket:%d\n", td->GetName(), ticket);
            ticket--;
            pthread_mutex_unlock(td->GetPlock());
        }
        else
        {
            pthread_mutex_unlock(td->GetPlock());
            break;
        }
    }
    return NULL;
}

int main(void)
{
    pthread_mutex_t lock;
    pthread_mutex_init(&lock, NULL);
    pthread_t t1, t2, t3, t4;

    ThreadData *td1 = new ThreadData("Thread-1", lock);
    pthread_create(&t1, NULL, route, td1);

    ThreadData *td2 = new ThreadData("Thread-2", lock);
    pthread_create(&t2, NULL, route, td2);

    ThreadData *td3 = new ThreadData("Thread-3", lock);
    pthread_create(&t3, NULL, route, td3);

    ThreadData *td4 = new ThreadData("Thread-4", lock);
    pthread_create(&t4, NULL, route, td4);

    pthread_join(t1, NULL);
    pthread_join(t2, NULL);
    pthread_join(t3, NULL);
    pthread_join(t4, NULL);

    pthread_mutex_destroy(&lock);

    return 0;
}
